import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

#功能1：图像的读取,由于给的图像较大，所以我把图像的长宽都变成原来的0.45倍
def readImg(path):
    img1=cv.imread(path)
    width,height = img1.shape[:2][::-1]
    img2=cv.resize(img1,(int(width*0.5),int(height*0.5)),interpolation=cv.INTER_CUBIC)#把图形变小显示
    return img2


#功能2：图像的显示
def show(src,flag):
    win=cv.namedWindow(flag)
    cv.imshow(flag, src)


#真彩图像转灰度图像：遍历每个像素点，对其进行gamma校正，gamma取值为2.2
def transColorImgToGray(img):
    grayImg=img.copy()
    w,h=grayImg.shape[:2][::-1]
    for i in range(0,h):
        for j in range(0,w):
            x=int((1*img[i,j][2])**2.2)+int((1.5*img[i,j][1])**2.2)+int((0.6*img[i,j][0])**2.2)
            y=1**2.2+1.5**2.2+0.6**2.2
            grayImg[i,j]=int((x/y)**(1/2.2))
    gWindow=cv.namedWindow("greyImg")
    cv.imshow("greyImg",grayImg)
    return grayImg


#灰度图转换成二值图：先求图像的平均灰度值avg，然后遍历每个像素点，若其灰度小于avg,就将其变成0；否则变成255
def binaryImg(img):
    brayImg = img.copy()
    w, h = brayImg.shape[:2][::-1]
    avg = int(np.average(brayImg))
    for i in range(0,h):
        for j in range(0,w):
            if any(img[i,j]<=avg):
                brayImg[i,j]=0
            else:
                brayImg[i,j]=255
    bWindow = cv.namedWindow("binaryImg")
    cv.imshow("binaryImg", brayImg)
    return brayImg


#绘制图像直方图
def drawHist(img):
    plt.hist(img.ravel(), 256, [0, 256])
    plt.xlim([0,256])
    plt.show()


if __name__ == '__main__':
    path="./flowers.tif"
    img=readImg(path)
    show(img,"rawImg")
    grayImg=transColorImgToGray(img)
    bImg=binaryImg(grayImg)
    drawHist(img)
    cv.waitKey(0)
    cv.destroyAllWindows()
